package com.easy.controller;

import com.easy.bean.Inventory;
import com.easy.bean.MonthlySum;
import java.util.ArrayList; // 导入 ArrayList 类
import java.util.List; // 导入 List 接口
import com.easy.bean.Order;
import com.easy.common.CommonResult;
import com.easy.common.OrderResult;
import com.easy.common.MonthlySumResult;
import com.easy.common.YearlySumResult;
import com.easy.dao.IInventoryDao;
import com.easy.dao.IOrderDao;
import com.easy.dao.IOutOrderDao;
import com.easy.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private IInInventoryService iis;
    @Autowired
    private IOutInventoryService ois;
    @Autowired
    private IInOrderService ios;
    @Autowired
    private IOutOrderService oos;
    @Autowired
    private IInventoryService is;
    @Autowired
    private IInventoryDao dao;
    @Autowired
    private IOutOrderDao odao;
    @Autowired
    private IOrderDao iOrderDao;


    // 查询某个月的出库和入库总金额
    @GetMapping("/monthly/sums")
    public MonthlySumResult getMonthlySummary(@RequestParam("year") int year, @RequestParam("month") int month) {
        BigDecimal totalInSum = iOrderDao.getInSumsByMonth(year, month);
        BigDecimal totalOutSum = iOrderDao.getOutSumsByMonth(year, month);
        return MonthlySumResult.success(totalInSum, totalOutSum);
    }


    // 查询某一年的出库和入库总金额
    @GetMapping("/yearly/sums")
    public YearlySumResult getYearlySummary(@RequestParam("year") int year) {
        List<BigDecimal> totalInSums = new ArrayList<>();
        List<BigDecimal> totalOutSums = new ArrayList<>();

        for (int month = 1; month <= 12; month++) {
            BigDecimal totalInSum = iOrderDao.getInSumsByMonth(year, month);
            BigDecimal totalOutSum = iOrderDao.getOutSumsByMonth(year, month);
            totalInSums.add(totalInSum != null ? totalInSum : BigDecimal.ZERO); // 确保数据不为 null
            totalOutSums.add(totalOutSum != null ? totalOutSum : BigDecimal.ZERO); // 确保数据不为 null
        }

        return new YearlySumResult(year, totalInSums, totalOutSums);
    }


    // 统计订单数量
    @GetMapping("/count")
    public OrderResult<Map<String, Integer>> getOrderCounts(){
        int inOrderCount = iOrderDao.countInOrders();
        int outOrderCount = iOrderDao.countOutOrder();

        // Use HashMap to initialize the map with constants
        Map<String, Integer> orderCounts = new HashMap<>();
        orderCounts.put("入库订单量", inOrderCount);
        orderCounts.put("出库订单量", outOrderCount);

        return OrderResult.success(orderCounts);
    }


    @Transactional
    @PostMapping("/inadds")
    public CommonResult addOrdersAndInventory(@RequestBody Order order) {
        // 检查订单是否为空
        if (order == null || order.getList() == null || order.getList().isEmpty()) {
            return CommonResult.fail("订单列表为空");
        }

        // 检查 in_id 是否有效
        String inId = order.getIn_id();
        if (inId == null || inId.isEmpty()) {
            return CommonResult.fail("无效的 in_id");
        }

        // 处理库存添加
        int inventoryCount = iis.addInInventory(order);
        if (inventoryCount <= 0) {
            return CommonResult.fail("库存添加失败");
        }


        // 处理每个订单项
        for (Order item : order.getList()) {
            item.setIn_id(inId); // 确保每个订单项使用相同的 in_id
            item.setIn_date(order.getIn_date()); // 确保每个订单项的日期一致

//            System.out.println("----------------"+item.toString()+"------------");

            // 检查订单项的 product_id 和数量
            if (item.getProduct_id() == null || item.getProduct_id().isEmpty()) {
                return CommonResult.fail("订单项的 product_id 不能为空");
            }

            if (item.getIn_num() <= 0 && item.getOut_num() <= 0) {
                return CommonResult.fail("订单项的入库数量或出库数量必须大于零");
            }

            // 处理入库
            if (item.getIn_num() > 0) {
                int inNum = item.getIn_num();

                // 获取当前库存
                Inventory existingInventory = is.getInventoryByProductId(item.getProduct_id());
                if (existingInventory == null) {
                    return CommonResult.fail("商品不存在: " + item.getProduct_id());
                }

                // 更新库存数量
                int newNumber = existingInventory.getNumber() + inNum;
                existingInventory.setNumber(newNumber);
                int count = dao.editInventory(existingInventory);
                if (count <= 0) {
                    return CommonResult.fail("库存更新失败: " + item.getProduct_id());
                }

                // 添加订单项
                int orderCount = ios.addInOrder(item);
                if (orderCount <= 0) {
                    return CommonResult.fail("订单项添加失败");
                }

            } else if (item.getOut_num() > 0) {
                int outNum = item.getOut_num();

                // 获取当前库存
                Inventory existingInventory = is.getInventoryByProductId(item.getProduct_id());
                if (existingInventory == null) {
                    return CommonResult.fail("商品不存在: " + item.getProduct_id());
                }

                // 检查出库数量是否大于当前库存
                if (outNum > existingInventory.getNumber()) {
                    return CommonResult.fail("出库数量不能大于当前库存量: " + item.getProduct_id());
                }

                // 更新库存数量
                int newNumber = existingInventory.getNumber() - outNum;
                existingInventory.setNumber(newNumber);
                int count = dao.editInventory(existingInventory);
                if (count <= 0) {
                    return CommonResult.fail("库存更新失败: " + item.getProduct_id());
                }

                // 添加订单项
                int orderCount = oos.addOutOrder(item); // 确保此方法是用于处理出库订单项的
                if (orderCount <= 0) {
                    return CommonResult.fail("订单项添加失败");
                }

            } else {
                return CommonResult.fail("订单项的入库数量或出库数量必须大于零");
            }
        }

        return CommonResult.success("订单和库存处理成功");
    }

    @Transactional
    @PostMapping("/outadds")
    public CommonResult addOrderAndInventoryOut(@RequestBody Order order) {
        boolean bool = false;//判断是否有出库数大于库存数
        if (order == null) {
            return CommonResult.fail("订单为空");
        }

        String outId = order.getOut_id();
        if (outId == null || outId.isEmpty()) {
            return CommonResult.fail("无效的 out_id");
        }


        // 处理每个订单项
        for (Order item : order.getList()) {

            item.setOut_id(outId); // 确保每个订单项使用相同的 out_id
            item.setOut_date(order.getOut_date()); // 确保每个订单项的日期一致
            // 获取当前库存
            Inventory existingInventory = is.getInventoryByProductId(item.getProduct_id());
            if (existingInventory == null) {
                return CommonResult.fail("商品不存在: " + item.getProduct_id());
            }

            // 检查出库数量是否大于当前库存
            int outNum = item.getOut_num();
            if (outNum >= existingInventory.getNumber()) {
                bool  = true;
                return CommonResult.fail("出库数量不能大于当前库存量: " + item.getProduct_id());
            }
//            // 更新出库价格
//            existingInventory.setIn_price(item.getIn_price());

            // 更新库存数量
            int newNumber = existingInventory.getNumber() - outNum;
            existingInventory.setNumber(newNumber);
            int count = dao.editInventory(existingInventory);
            if (count <= 0) {
                return CommonResult.fail("库存更新失败: " + item.getProduct_id());
            }

            // 添加订单项
            int orderCount = oos.addOutOrder(item); // 确保此方法是用于处理出库订单项的
            if (orderCount <= 0) {
                return CommonResult.fail("订单项添加失败");
            }
        }
        // 处理库存添加

        if(!bool) {
            int inventoryCount = ois.addOutInventory(order);
            if (inventoryCount <= 0) {
                return CommonResult.fail("库存添加失败");
            }
        }

        return CommonResult.success("订单和库存出库成功");
    }




}

